import React, { useState, useMemo } from 'react';
import { Table, Card, Typography, Empty, Input, Select, Space, Tag, Button, Tooltip } from 'antd';
import { SearchOutlined, FilterOutlined, ReloadOutlined, DownloadOutlined, TableOutlined } from '@ant-design/icons';
import { TableData } from '../../KimiChat';
import './DataTable.scss';

const { Title, Text } = Typography;
const { Option } = Select;

interface DataTableProps {
    tableData: TableData[];
    conversationId: string | null;
}

const DataTable: React.FC<DataTableProps> = ({ tableData, conversationId }) => {
    const [searchText, setSearchText] = useState('');
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [categoryFilter, setCategoryFilter] = useState<string>('all');

    // 获取唯一的状态和类别选项
    const { statusOptions, categoryOptions } = useMemo(() => {
        const statuses = Array.from(new Set(tableData.map(item => item.status)));
        const categories = Array.from(new Set(tableData.map(item => item.category)));
        
        return {
            statusOptions: statuses.map(status => ({ label: status, value: status })),
            categoryOptions: categories.map(category => ({ label: category, value: category }))
        };
    }, [tableData]);

    // 过滤数据
    const filteredData = useMemo(() => {
        return tableData.filter(item => {
            const matchesSearch = !searchText || 
                item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                item.category.toLowerCase().includes(searchText.toLowerCase());
            
            const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
            const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;
            
            return matchesSearch && matchesStatus && matchesCategory;
        });
    }, [tableData, searchText, statusFilter, categoryFilter]);

    // 重置筛选
    const handleReset = () => {
        setSearchText('');
        setStatusFilter('all');
        setCategoryFilter('all');
    };

    // 导出数据
    const handleExport = () => {
        if (filteredData.length === 0) {
            return;
        }
        
        const csvContent = [
            ['ID', '名称', '数值', '类别', '状态', '日期'].join(','),
            ...filteredData.map(item => [
                item.id,
                item.name,
                item.value,
                item.category,
                item.status,
                item.date
            ].join(','))
        ].join('\n');
        
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `data_${conversationId}_${new Date().getTime()}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    // 获取状态标签颜色
    const getStatusColor = (status: string) => {
        const colorMap: { [key: string]: string } = {
            '成功': 'success',
            '失败': 'error',
            '处理中': 'processing',
            '等待': 'warning',
            '完成': 'success',
            '错误': 'error',
            '正常': 'success',
            '异常': 'error'
        };
        return colorMap[status] || 'default';
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 120,
            ellipsis: {
                showTitle: false,
            },
            render: (text: string) => (
                <Tooltip title={text}>
                    <Text code className="data-table__id">{text}</Text>
                </Tooltip>
            ),
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: {
                showTitle: false,
            },
            render: (text: string) => (
                <Tooltip title={text}>
                    <Text strong>{text}</Text>
                </Tooltip>
            ),
        },
        {
            title: '数值',
            dataIndex: 'value',
            key: 'value',
            width: 100,
            align: 'right' as const,
            sorter: (a: TableData, b: TableData) => a.value - b.value,
            render: (value: number) => (
                <Text className="data-table__value">
                    {value.toLocaleString()}
                </Text>
            ),
        },
        {
            title: '类别',
            dataIndex: 'category',
            key: 'category',
            width: 100,
            render: (category: string) => (
                <Tag className="data-table__category">{category}</Tag>
            ),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 80,
            render: (status: string) => (
                <Tag color={getStatusColor(status)} className="data-table__status">
                    {status}
                </Tag>
            ),
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            width: 120,
            sorter: (a: TableData, b: TableData) => new Date(a.date).getTime() - new Date(b.date).getTime(),
            render: (date: string) => (
                <Text type="secondary" className="data-table__date">
                    {new Date(date).toLocaleDateString('zh-CN')}
                </Text>
            ),
        },
    ];

    return (
        <div className="data-table">
            <Card 
                className="data-table__card"
                title={
                    <div className="data-table__header">
                        <Space>
                            <TableOutlined />
                            <Title level={4} className="data-table__title">
                                数据表格
                            </Title>
                        </Space>
                        <Text type="secondary" className="data-table__count">
                            {filteredData.length} / {tableData.length}
                        </Text>
                    </div>
                }
                extra={
                    <Space>
                        <Tooltip title="导出数据">
                            <Button
                                icon={<DownloadOutlined />}
                                onClick={handleExport}
                                disabled={filteredData.length === 0}
                                size="small"
                            />
                        </Tooltip>
                        <Tooltip title="重置筛选">
                            <Button
                                icon={<ReloadOutlined />}
                                onClick={handleReset}
                                size="small"
                            />
                        </Tooltip>
                    </Space>
                }
                bodyStyle={{ padding: 0 }}
            >
                {/* 筛选区域 */}
                {tableData.length > 0 && (
                    <div className="data-table__filters">
                        <Space direction="vertical" className="data-table__filters-content">
                            <Input
                                placeholder="搜索名称或类别..."
                                prefix={<SearchOutlined />}
                                value={searchText}
                                onChange={(e) => setSearchText(e.target.value)}
                                allowClear
                                className="data-table__search"
                            />
                            <Space className="data-table__filter-selects">
                                <Select
                                    placeholder="状态筛选"
                                    value={statusFilter}
                                    onChange={setStatusFilter}
                                    className="data-table__filter-select"
                                    suffixIcon={<FilterOutlined />}
                                >
                                    <Option value="all">全部状态</Option>
                                    {statusOptions.map(option => (
                                        <Option key={option.value} value={option.value}>
                                            {option.label}
                                        </Option>
                                    ))}
                                </Select>
                                <Select
                                    placeholder="类别筛选"
                                    value={categoryFilter}
                                    onChange={setCategoryFilter}
                                    className="data-table__filter-select"
                                    suffixIcon={<FilterOutlined />}
                                >
                                    <Option value="all">全部类别</Option>
                                    {categoryOptions.map(option => (
                                        <Option key={option.value} value={option.value}>
                                            {option.label}
                                        </Option>
                                    ))}
                                </Select>
                            </Space>
                        </Space>
                    </div>
                )}

                {/* 表格内容 */}
                <div className="data-table__content">
                    {tableData.length === 0 ? (
                        <div className="data-table__empty">
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={
                                    <>
                                        <Text strong>暂无数据</Text>
                                        <br />
                                        <Text type="secondary">
                                            {conversationId ? '发送消息后将显示相关数据' : '请选择对话查看数据'}
                                        </Text>
                                    </>
                                }
                            />
                        </div>
                    ) : (
                        <Table
                            columns={columns}
                            dataSource={filteredData}
                            rowKey="id"
                            size="small"
                            pagination={{
                                pageSize: 10,
                                showSizeChanger: true,
                                showQuickJumper: true,
                                showTotal: (total, range) => 
                                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                                className: 'data-table__pagination'
                            }}
                            scroll={{ y: 400 }}
                            className="data-table__table"
                        />
                    )}
                </div>
            </Card>
        </div>
    );
};

export default DataTable;